define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form,Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'user/userinput/index' + location.search,
                    add_url: 'user/userinput/add',
                    edit_url: 'user/userinput/edit',
                    del_url: 'user/userinput/del',
                    detail_url: 'user/userinput/detail',
                    gradeadd_url: 'user/userinput/gradeadd',
                    gradeedit_url: 'user/userinput/gradeedit',
                    gradedel_url: 'user/userinput/gradedel',
                    multi_url: 'user/userinput/multi',
                    table: 'org_cate'
                }
            });

            var table = $("#table");
             table.on('load-success.bs.table', function (e, data) {
                 //这里可以获取从服务端获取的JSON数据
                 //这里我们手动设置底部的值
                  $("#current_img").text(data.current.avatar);
                 $("#current_phone").text(data.current.mobile);
                 $("#current_name").text(data.current.name);
                 $("#current_time").text(data.current.createtime);
                 $("#username").text(data.current.username);
             });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                escape: false,
                columns: [
                    [
                        //{checkbox: true},
                        {
                            field: 'id',
                            title: '<a href="javascript:;" class="btn btn-success btn-xs btn-toggle"><i class="fa fa-chevron-up"></i></a>',
                            operate: false,
                            formatter: Controller.api.formatter.subnode
                        },
                        {field: 'id', title: __('单位编号'), operate:false},
                        {field: 'name', title: __('Name'), align: 'left', operate:'LIKE'},
                        // {field: 'parent_id', title: __('Parent_id'), operate:false},
                        // {field: 'level', title: __('Level'), operate:false},
                        // {field: 'reg_user_num', title: __('Reg_user_num'), operate:false},
                        // {field: 'visitor_user_num', title: __('Visitor_user_num'), operate:false},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'introduce', title: __('Introduce'), operate:false},
                       /* {field: 'status', title: __('Status'), operate:false, searchList: {"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},*/
                        // {field: 'mobile', title: __('Mobile'), operate:'LIKE'},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            // formatter: Controller.api.formatter.operate,
                            buttons: [
                                // {
                                //     name: 'importdialog',
                                //     title: __('导入学生家长或教职工'),
                                //     text:'导入学生家长或教职工',
                                //     classname: 'btn btn-xs btn-info btn-selected btn-dialog',
                                //     icon: 'fa fa-plus',
                                //     url: 'user/userinput/importdialog',
                                //     extend: 'data-area=["100%","100%"]',
                                //     callback: function (data) {
                                //         console.log('data',data);
                                //         // Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                //         $(".btn-refresh").trigger("click");
                                //     }
                                // },
                                {
                                    name: 'detail',
                                    title: __('学生和家长名单录入'),
                                    text: __('学生和家长名单录入'),
                                    classname: 'btn btn-xs btn-info btn-addtabs btn-ajax',
                                    icon: 'fa fa-folder-o',
                                    url: 'user/userinput/detail'+ location.search
                                },
                                {
                                    name: 'detail2',
                                    title: __('教职员工名单录入'),
                                    text: __('教职员工名单录入'),
                                    classname: 'btn btn-xs btn-warning btn-addtabs btn-ajax',
                                    icon: 'fa fa-folder-o',
                                    url: 'user/userinput/detail2'+ location.search
                                }
                            ]

                        }
                    ]
                ],
                pagination: false,
                showToggle: false,
                showColumns: false,
                showExport: false,
                searchFormVisible: false,
                commonSearch: false,
                search:true,
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-editone").data("area", ["100%","100%"]);
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            if($(Table.config.importbtn).size() > 0){
                require(['upload'], function(Upload){
                    Upload.api.plupload($(Table.config.importbtn), function(data, res){
                        Toastr.success(res.msg);
                        table.bootstrapTable('refresh');
                    }, function(res){
                        Toastr.success(res.msg);
                    })
                })
            }
            $(".btn-selected").on('click',function(){
                Fast.api.open('user/userinput/importdialog', '导入', {
                    area:["100%","100%"],
                    callback:function(){
                        $(".btn-refresh").trigger('click');//刷新当前页面的数据

                    }
                })
            });
            //当内容渲染完成后
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                //默认隐藏所有子节点
                //$("a.btn[data-id][data-pid][data-pid!=0]").closest("tr").hide();
                $(".btn-node-sub.disabled").closest("tr").hide();
                $(".btn-node-sub.btn-hidden").closest("tr").hide();

                //显示隐藏子节点
                $(".btn-node-sub").off("click").on("click", function (e) {
                    var status = $(this).data("shown") ? true : false;
                    $("a.btn[data-pid='" + $(this).data("id") + "']").each(function (e) {
                        $(this).closest("tr").toggle(!status);
                    });
                    if(status){
                        $(this).children("i").removeClass('fa-minus').addClass('fa-plus');
                    }else{
                        $(this).children("i").removeClass('fa-plus').addClass('fa-minus');
                    }

                    $(this).data("shown", !status);
                    return false;
                });
                //点击切换/排序/删除操作后刷新左侧菜单
                $(".btn-change[data-id],.btn-delone,.btn-dragsort").data("success", function (data, ret) {
                    Fast.api.refreshmenu();
                    return false;
                });

            });
            //批量删除后的回调
            $(".toolbar > .btn-del,.toolbar .btn-more~ul>li>a").data("success", function (e) {
                Fast.api.refreshmenu();
            });
            //展开隐藏一级
            // $(document.body).on("click", ".btn-toggle", function (e) {
            //     $("a.btn[data-id][data-pid][data-pid!=0].disabled").closest("tr").hide();
            //     var that = this;
            //     var show = $("i", that).hasClass("fa-chevron-down");
            //     $("i", that).toggleClass("fa-chevron-down", !show);
            //     $("i", that).toggleClass("fa-chevron-up", show);
            //     $("a.btn[data-id][data-pid][data-pid!=0]").not('.disabled').closest("tr").toggle(show);
            //     $(".btn-node-sub[data-pid=0]").data("shown", show);
            // });
            //展开隐藏全部
            $(document.body).on("click", ".btn-toggle-all", function (e) {
                var that = this;
                var show = $("i", that).hasClass("fa-plus");
                $("i", that).toggleClass("fa-plus", !show);
                $("i", that).toggleClass("fa-minus", show);
                $(".btn-node-sub.disabled").closest("tr").toggle(show);
                $(".btn-node-sub").data("shown", show);
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            Table.api.init({
                extend: {
                    chapter_url: 'user/userinput/detail'+ location.search,
                    table: 'user_userinput_detail'
                }
            });
            var table1 = $('#table1');
            table1.on('post-common-search.bs.table', function (event, table) {
                $(".commonsearch-table").find('.btn-success').html('搜索');
                $(".commonsearch-table").find('.btn-default').html('刷新');
                $(".columns-right").hide();
                $('.form-commonsearch').attr('autocomplete', 'off');
            });
            table1.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.chapter_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'sort', title: __('序号'),operate: false},
                        {field: 'number_id', title:'学生学号',operate: false},
                        //{field: 'username', title: __('Username'),operate: false},
                        {field: 'nickname', title:'学生姓名', operate: false},
                        {field: 'gender', title: __('Gender'),operate: false, visible: true, formatter: Table.api.formatter.normal, searchList: {1: __('Male'), 2: __('Female')}},
                        {field: 'age', title: __('年龄'), operate: false},
                        {field: 'username', title: __('Username'),operate: false},
                        {field: 'pwd', title: __('用户密码'),operate: false},
                        {field: 'pusername', title:'家长用户名', operate: false},
                        {field: 'spwd', title:'家长密码', operate: false},
                        // {field: 'group.name', title: __('Group')},
                        //{field: 'user_type', title: __('Type'), formatter: Table.api.formatter.normal, searchList: {'0' : __('Type 0'), '1': __('Type 1'),'3' : __('Type 3')},operate: false},

                        // {field: 'org_cate_id', title:__('Org_cate_id'), operate: false},
                        //{field: 'org_grade_name', title:'班号',operate: false},
                        //{field: 'orggroup.org_grade_id', title:'班号',visible: false,
                        //    searchList: $.getJSON('user/userinput/searchlist')
                        //},
                        //{field: 'o.number', title:'班号',visible: false, operate: 'like'},
                        //{field: 'nickname', title: __('Nickname'),operate: false},
                        //{field: 'email', title: __('Email'),operate: false},
                        //{field: 'mobile', title: __('Mobile'),operate: false},
                        //{field: 'avatar', title: __('Avatar'),operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        // {field: 'level', title: __('Level'), operate: false, sortable: true},
                        //{field: 'score', title: __('Score'), operate: false, sortable: true},
                        // {field: 'successions', title: __('Successions'), visible: false, operate: false, sortable: true},
                        // {field: 'maxsuccessions', title: __('Maxsuccessions'), visible: false, operate: false, sortable: true},
                        // {field: 'logintime', title: __('Logintime'), operate: false, formatter: Table.api.formatter.datetime, addclass: 'datetimerange', sortable: true},
                        // {field: 'loginip', title: __('Loginip'), operate: false, formatter: Table.api.formatter.search},
                        // {field: 'jointime', title: __('Jointime'), operate: false, formatter: Table.api.formatter.datetime, addclass: 'datetimerange', sortable: true},
                        // {field: 'joinip', title: __('Joinip'), operate: false, formatter: Table.api.formatter.search},
                        //{field: 'status', title: __('Status'),operate: false, formatter: Table.api.formatter.status, searchList: {normal: __('Normal'), hidden: __('Hidden')}},
                        {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'useredit',
                                    title: __('编辑'),
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: 'fa fa-pencil',
                                    // url: 'user/userinput/useredit'+ location.search,
                                    click: function (data,row) {
                                        edituser(row.id);
                                        // Layer.alert("点击按钮执行的事件");
                                    }
                                },
                                {
                                    name: 'userdel',
                                    title: __('Delete'),
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    icon: 'fa fa-trash',
                                    click: function (data,row) {
                                        confirmf(row.id);
                                        // Layer.alert("点击按钮执行的事件");
                                    }
                                }
                            ]

                        }
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
                searchFormVisible: false,
                search:false,
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-editone").data("area", ["100%","100%"]);
                    $(".columns-right").hide();
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table1);
            var confirmf = function(id){
                Layer.confirm("确定删除该用户吗？",
                    {
                        title: '删除用户',
                        btn: ["确定", "取消"],
                        yes: function (index, layero) {
                            submitExportForm(id,index, layero);
                            return false;
                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                            return false;
                        },
                    });
            }
            var submitExportForm = function (id,index, layero) {
                var data = {
                    ids: id
                };
                Fast.api.ajax({
                    url: Fast.api.fixurl('user/userinput/userdel'),
                    data: data,
                    pk: 'id'
                }, function (res) {
                    Layer.closeAll();
                    Fast.api.close(layero.selector);
                    $(".btn-refresh").trigger("click");
                });
            };
            $(".btn-selected").on('click',function(){
                var ids = $(this).data('ids');
                console.log('ids',ids);
                Fast.api.open('user/userinput/importdialog?ids='+ids, '导入', {
                    area:["100%","100%"],
                    callback:function(){
                        $(".btn-refresh").trigger('click');//刷新当前页面的数据

                    }
                })
            });
            var edituser = function (id) {
                console.log('id',id)
                Fast.api.open('user/userinput/useredit?ids='+id, '编辑', {
                    area:["100%","100%"],
                    callback:function(){
                        Fast.api.close();
                        $(".btn-refresh").trigger('click');//刷新当前页面的数据
                    }
                })
            }
        },
        useradd: function () {
            Controller.api.bindevent();
        },
        useredit: function () {
            Controller.api.bindevent();
        },
        userdel: function () {
            Controller.api.bindevent();
        },

        import: function () {
            Controller.api.bindevent();
        },
        importdialog:function(){
            if($(Table.config.importbtn).size() > 0){
                require(['upload'], function(Upload){
                    Upload.api.plupload($(Table.config.importbtn), function(data, res, layero){
                        Toastr.success(res.msg);
                        Layer.closeAll();
                        Fast.api.close();
                    }, function(res){
                        //console.log('res222', res);
                        //Toastr.success(res.msg);
                    })
                })
            }
            Controller.api.bindevent();
        },
        detail2: function () {
            Table.api.init({
                extend: {
                    chapter_url: 'user/userinput/detail2'+ location.search,
                    import2_url: 'user/userinput/import2',
                    table: 'user_userinput_detail2'
                }
            });
            var table2 = $('#table2');
            table2.on('post-common-search.bs.table', function (event, table) {
                $(".commonsearch-table").find('.btn-success').html('搜索');
                $(".commonsearch-table").find('.btn-default').html('刷新');
                $(".columns-right").hide();
                $('.form-commonsearch').attr('autocomplete', 'off');
            });
            table2.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.chapter_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'sort', title: __('序号')},
                        {field: 'number_id', title:'工号', operate: false},
                        {field: 'nickname', title: __('姓名'), operate: false},
                        {field: 'gender', title: __('Gender'), visible: false,  formatter: Table.api.formatter.normal,searchList: {1: __('Male'), 2: __('Female')}},
                        {field: 'age', title: __('年龄'), operate: false},
                        {field: 'username', title: __('Username'), operate: 'LIKE'},
                        {field: 'pwd', title: __('密码'), operate: false},
                         {field: 'postname', title: __('职务类型'), operate: false},
                        //{field: 'user_type', title: __('Type'), formatter: Table.api.formatter.normal, searchList: {'0' : __('Type 0'), '1': __('Type 1'),'3' : __('Type 3')}},

                        // {field: 'org_cate_id', title:__('Org_cate_id'), operate: false},

                        //{field: 'pusername', title:'学生家长名称', operate: false},
                        //{field: 'susername', title:'家长的学生名称', operate: false},

                        //{field: 'email', title: __('Email'), operate: 'LIKE'},
                        //{field: 'mobile', title: __('Mobile'), operate: 'LIKE'},
                        //{field: 'avatar', title: __('Avatar'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        // {field: 'level', title: __('Level'), operate: false, sortable: true},

                        //{field: 'score', title: __('Score'), operate: false, sortable: true},
                        // {field: 'successions', title: __('Successions'), visible: false, operate: false, sortable: true},
                        // {field: 'maxsuccessions', title: __('Maxsuccessions'), visible: false, operate: false, sortable: true},
                        // {field: 'logintime', title: __('Logintime'), operate: false, formatter: Table.api.formatter.datetime, addclass: 'datetimerange', sortable: true},
                        // {field: 'loginip', title: __('Loginip'), operate: false, formatter: Table.api.formatter.search},
                        // {field: 'jointime', title: __('Jointime'), operate: false, formatter: Table.api.formatter.datetime, addclass: 'datetimerange', sortable: true},
                        // {field: 'joinip', title: __('Joinip'), operate: false, formatter: Table.api.formatter.search},
                        //{field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {normal: __('Normal'), hidden: __('Hidden')}},
                        {field: 'operate', title: __('Operate'),
                            table: table2,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'useredit2',
                                    title: __('编辑'),
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: 'fa fa-pencil',
                                    click: function (data,row) {
                                        edituser(row.id);
                                        // Layer.alert("点击按钮执行的事件");
                                    }
                                },
                                {
                                    name: 'userdel2',
                                    title: __('Delete'),
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    icon: 'fa fa-trash',
                                    click: function (data,row) {
                                        confirmf(row.id);
                                        // Layer.alert("点击按钮执行的事件");
                                    }
                                }
                            ],
                            formatter: Table.api.formatter.operate}
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
                searchFormVisible: false,
                search:false,
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-editone").data("area", ["100%","100%"]);
                    $(".columns-right").hide();
                }
            });
            if($(Table.config.importbtn).size() > 0){
                require(['upload'], function(Upload){
                    Upload.api.plupload($(Table.config.importbtn), function(data, res, layero){
                        Toastr.success(res.msg);
                        Layer.closeAll();
                        Fast.api.close();
                        $(".btn-refresh").trigger('click');//刷新当前页面的数据
                    }, function(res){
                        //console.log('res222', res);
                        //Toastr.success(res.msg);
                    })
                })
            }
            // 为表格绑定事件
            Table.api.bindevent(table2);
            var confirmf = function(id){
                Layer.confirm("确定删除该教职工吗？",
                    {
                        title: '删除教职工',
                        btn: ["确定", "取消"],
                        yes: function (index, layero) {
                            submitExportForm(id,index, layero);
                            return false;
                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                            return false;
                        },
                    });
            }
            var submitExportForm = function (id,index, layero) {
                var data = {
                    ids: id
                };
                Fast.api.ajax({
                    url: Fast.api.fixurl('user/userinput/userdel2'),
                    data: data,
                    pk: 'id'
                }, function (res) {
                    Layer.closeAll();
                    Fast.api.close(layero.selector);
                    $(".btn-refresh").trigger("click");
                });
            };
            $(document).on("click", ".btn-selected", function () {
                var ids = Table.api.selectedids(table2);  //所有选中的项
                Layer.confirm("确定删除选中的"+ ids.length +"个教职工吗？",
                    {
                        title: '批量删除教职工',
                        btn: ["确定", "取消"],
                        yes: function (index, layero) {
                            submitExportForm(ids.join(","), layero, index);
                            return false;
                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                            return false;
                        },
                    });
            });
            var edituser = function (id) {
                console.log('id',id)
                Fast.api.open('user/userinput/useredit2?ids='+id, '编辑', {
                    area:["100%","100%"],
                    callback:function(){
                        Fast.api.close();
                        $(".btn-refresh").trigger('click');//刷新当前页面的数据
                    }
                })
            };



        },
        useradd2: function () {
            Controller.api.bindevent();
        },
        useredit2: function () {
            Controller.api.bindevent();
        },
        userdel2: function () {
            Controller.api.bindevent();
        },
        import2: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter: {
                subnode: function (value, row, index) {
                    return '<a href="javascript:;" data-toggle="tooltip" title="' + __('Toggle sub menu') + '" data-id="' + row.id + '" data-pid="' + row.pid + '" class="btn btn-xs btn-success '+ (row.level == 3? 'btn-hidden' : '') + ' btn-node-sub">'+ (row.level == 3? '' : '<i class="fa fa-plus"></i>')+'</a>';
                },
                operate: function (value, row, index) {
                    return '<a href="/admin/user/userinput/add/ids/' + row.id + '" class="btn btn-xs btn-success btn-dialog '+ (row.level == 3? 'disabled' : '')+'" data-area="[&quot;100%&quot;,&quot;100%&quot;]" title="添加下级单位" data-table-id="table" data-field-index="10" data-row-index="' +index + '" data-button-index="0"><i class="fa fa-plus"></i> 添加下级单位</a>&nbsp;&nbsp;' +
                        '<a href="/admin/user/userinput/grade?addtabs=1&amp;ids=' + row.id + '" class="btn btn-xs btn-warning btn-addtabs btn-ajax" title="添加学校班号" data-table-id="table" data-field-index="10" data-row-index="' +index + '" data-button-index="1"><i class="fa fa-folder-o"></i> 添加学校班号</a>&nbsp;&nbsp;' +
                        '<a href="/admin/user/userinput/edit/ids/' + row.id + '" class="btn btn-xs btn-success btn-editone '+ (row.level == 1? 'disabled' : '')+'" data-toggle="tooltip" title="" data-table-id="table" data-field-index="10" data-row-index="' +index + '" data-button-index="3" data-original-title="编辑"><i class="fa fa-pencil"></i></a>&nbsp;&nbsp;' +
                        '<a href="javascript:;" class="btn btn-xs btn-danger btn-delone '+ (row.level == 1? 'disabled' : '')+'" data-toggle="tooltip" title="删除" data-table-id="table" data-field-index="10" data-row-index="' +index + '" data-button-index="4"><i class="fa fa-trash"></i></a>';
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});